Maximum article size, since max_allowed_packet is too large on wikimedia these days...
[lhc/web/wiklou.git] / includes / EditPage.php
1 <?php
2 /**
3 * Contain the EditPage class
4 * @package MediaWiki
5 */
6
7 /**
8 * Splitting edit page/HTML interface from Article...
9 * The actual database and text munging is still in Article,
10 * but it should get easier to call those from alternate
11 * interfaces.
12 *
13 * @package MediaWiki
14 */
15
16 class EditPage {
17 var $mArticle;
18 var $mTitle;
19 var $mMetaData = '';
20 var $isConflict = false;
21 var $isCssJsSubpage = false;
22 var $deletedSinceEdit = false;
23 var $formtype;
24 var $firsttime;
25 var $lastDelete;
26 var $mTokenOk = true;
27 var $tooBig = false;
28 var $kblength = false;
29
30 # Form values
31 var $save = false, $preview = false, $diff = false;
32 var $minoredit = false, $watchthis = false, $recreate = false;
33 var $textbox1 = '', $textbox2 = '', $summary = '';
34 var $edittime = '', $section = '', $starttime = '';
35 var $oldid = 0, $editintro = '', $scrolltop = null;
36
37 /**
38 * @todo document
39 * @param $article
40 */
41 function EditPage( $article ) {
42 $this->mArticle =& $article;
43 global $wgTitle;
44 $this->mTitle =& $wgTitle;
45 }
46
47 /**
48 * This is the function that extracts metadata from the article body on the first view.
49 * To turn the feature on, set $wgUseMetadataEdit = true ; in LocalSettings
50 * and set $wgMetadataWhitelist to the *full* title of the template whitelist
51 */
52 function extractMetaDataFromArticle () {
53 global $wgUseMetadataEdit , $wgMetadataWhitelist , $wgLang ;
54 $this->mMetaData = '' ;
55 if ( !$wgUseMetadataEdit ) return ;
56 if ( $wgMetadataWhitelist == '' ) return ;
57 $s = '' ;
58 $t = $this->mArticle->getContent();
59
60 # MISSING : <nowiki> filtering
61
62 # Categories and language links
63 $t = explode ( "\n" , $t ) ;
64 $catlow = strtolower ( $wgLang->getNsText ( NS_CATEGORY ) ) ;
65 $cat = $ll = array() ;
66 foreach ( $t AS $key => $x )
67 {
68 $y = trim ( strtolower ( $x ) ) ;
69 while ( substr ( $y , 0 , 2 ) == '[[' )
70 {
71 $y = explode ( ']]' , trim ( $x ) ) ;
72 $first = array_shift ( $y ) ;
73 $first = explode ( ':' , $first ) ;
74 $ns = array_shift ( $first ) ;
75 $ns = trim ( str_replace ( '[' , '' , $ns ) ) ;
76 if ( strlen ( $ns ) == 2 OR strtolower ( $ns ) == $catlow )
77 {
78 $add = '[[' . $ns . ':' . implode ( ':' , $first ) . ']]' ;
79 if ( strtolower ( $ns ) == $catlow ) $cat[] = $add ;
80 else $ll[] = $add ;
81 $x = implode ( ']]' , $y ) ;
82 $t[$key] = $x ;
83 $y = trim ( strtolower ( $x ) ) ;
84 }
85 }
86 }
87 if ( count ( $cat ) ) $s .= implode ( ' ' , $cat ) . "\n" ;
88 if ( count ( $ll ) ) $s .= implode ( ' ' , $ll ) . "\n" ;
89 $t = implode ( "\n" , $t ) ;
90
91 # Load whitelist
92 $sat = array () ; # stand-alone-templates; must be lowercase
93 $wl_title = Title::newFromText ( $wgMetadataWhitelist ) ;
94 $wl_article = new Article ( $wl_title ) ;
95 $wl = explode ( "\n" , $wl_article->getContent() ) ;
96 foreach ( $wl AS $x )
97 {
98 $isentry = false ;
99 $x = trim ( $x ) ;
100 while ( substr ( $x , 0 , 1 ) == '*' )
101 {
102 $isentry = true ;
103 $x = trim ( substr ( $x , 1 ) ) ;
104 }
105 if ( $isentry )
106 {
107 $sat[] = strtolower ( $x ) ;
108 }
109
110 }
111
112 # Templates, but only some
113 $t = explode ( '{{' , $t ) ;
114 $tl = array () ;
115 foreach ( $t AS $key => $x )
116 {
117 $y = explode ( '}}' , $x , 2 ) ;
118 if ( count ( $y ) == 2 )
119 {
120 $z = $y[0] ;
121 $z = explode ( '|' , $z ) ;
122 $tn = array_shift ( $z ) ;
123 if ( in_array ( strtolower ( $tn ) , $sat ) )
124 {
125 $tl[] = '{{' . $y[0] . '}}' ;
126 $t[$key] = $y[1] ;
127 $y = explode ( '}}' , $y[1] , 2 ) ;
128 }
129 else $t[$key] = '{{' . $x ;
130 }
131 else if ( $key != 0 ) $t[$key] = '{{' . $x ;
132 else $t[$key] = $x ;
133 }
134 if ( count ( $tl ) ) $s .= implode ( ' ' , $tl ) ;
135 $t = implode ( '' , $t ) ;
136
137 $t = str_replace ( "\n\n\n" , "\n" , $t ) ;
138 $this->mArticle->mContent = $t ;
139 $this->mMetaData = $s ;
140 }
141
142 function submit() {
143 $this->edit();
144 }
145
146 /**
147 * This is the function that gets called for "action=edit". It
148 * sets up various member variables, then passes execution to
149 * another function, usually showEditForm()
150 *
151 * The edit form is self-submitting, so that when things like
152 * preview and edit conflicts occur, we get the same form back
153 * with the extra stuff added. Only when the final submission
154 * is made and all is well do we actually save and redirect to
155 * the newly-edited page.
156 */
157 function edit() {
158 global $wgOut, $wgUser, $wgRequest, $wgTitle,
159 $wgEmailConfirmToEdit;
160
161 if ( ! wfRunHooks( 'AlternateEdit', array( &$this ) ) )
162 return;
163
164 $fname = 'EditPage::edit';
165 wfProfileIn( $fname );
166 wfDebug( "$fname: enter\n" );
167
168 // this is not an article
169 $wgOut->setArticleFlag(false);
170
171 $this->importFormData( $wgRequest );
172 $this->firsttime = false;
173
174 if( $this->live ) {
175 $this->livePreview();
176 wfProfileOut( $fname );
177 return;
178 }
179
180 if ( ! $this->mTitle->userCanEdit() ) {
181 wfDebug( "$fname: user can't edit\n" );
182 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
183 wfProfileOut( $fname );
184 return;
185 }
186 wfDebug( "$fname: Checking blocks\n" );
187 if ( !$this->preview && !$this->diff && $wgUser->isBlockedFrom( $this->mTitle, !$this->save ) ) {
188 # When previewing, don't check blocked state - will get caught at save time.
189 # Also, check when starting edition is done against slave to improve performance.
190 wfDebug( "$fname: user is blocked\n" );
191 $wgOut->blockedPage();
192 wfProfileOut( $fname );
193 return;
194 }
195 if ( !$wgUser->isAllowed('edit') ) {
196 if ( $wgUser->isAnon() ) {
197 wfDebug( "$fname: user must log in\n" );
198 $this->userNotLoggedInPage();
199 wfProfileOut( $fname );
200 return;
201 } else {
202 wfDebug( "$fname: read-only page\n" );
203 $wgOut->readOnlyPage( $this->mArticle->getContent(), true );
204 wfProfileOut( $fname );
205 return;
206 }
207 }
208 if ($wgEmailConfirmToEdit && !$wgUser->isEmailConfirmed()) {
209 wfDebug("$fname: user must confirm e-mail address\n");
210 $this->userNotConfirmedPage();
211 wfProfileOut($fname);
212 return;
213 }
214 if ( !$this->mTitle->userCan( 'create' ) && !$this->mTitle->exists() ) {
215 wfDebug( "$fname: no create permission\n" );
216 $this->noCreatePermission();
217 wfProfileOut( $fname );
218 return;
219 }
220 if ( wfReadOnly() ) {
221 wfDebug( "$fname: read-only mode is engaged\n" );
222 if( $this->save || $this->preview ) {
223 $this->formtype = 'preview';
224 } else if ( $this->diff ) {
225 $this->formtype = 'diff';
226 } else {
227 $wgOut->readOnlyPage( $this->mArticle->getContent() );
228 wfProfileOut( $fname );
229 return;
230 }
231 } else {
232 if ( $this->save ) {
233 $this->formtype = 'save';
234 } else if ( $this->preview ) {
235 $this->formtype = 'preview';
236 } else if ( $this->diff ) {
237 $this->formtype = 'diff';
238 } else { # First time through
239 $this->firsttime = true;
240 if( $this->previewOnOpen() ) {
241 $this->formtype = 'preview';
242 } else {
243 $this->extractMetaDataFromArticle () ;
244 $this->formtype = 'initial';
245 }
246 }
247 }
248
249 wfProfileIn( "$fname-business-end" );
250
251 $this->isConflict = false;
252 // css / js subpages of user pages get a special treatment
253 $this->isCssJsSubpage = $wgTitle->isCssJsSubpage();
254
255 /* Notice that we can't use isDeleted, because it returns true if article is ever deleted
256 * no matter it's current state
257 */
258 $this->deletedSinceEdit = false;
259 if ( $this->edittime != '' ) {
260 /* Note that we rely on logging table, which hasn't been always there,
261 * but that doesn't matter, because this only applies to brand new
262 * deletes. This is done on every preview and save request. Move it further down
263 * to only perform it on saves
264 */
265 if ( $this->mTitle->isDeleted() ) {
266 $this->lastDelete = $this->getLastDelete();
267 if ( !is_null($this->lastDelete) ) {
268 $deletetime = $this->lastDelete->log_timestamp;
269 if ( ($deletetime - $this->starttime) > 0 ) {
270 $this->deletedSinceEdit = true;
271 }
272 }
273 }
274 }
275
276 if(!$this->mTitle->getArticleID() && ('initial' == $this->formtype || $this->firsttime )) { # new article
277 $this->showIntro();
278 }
279 if( $this->mTitle->isTalkPage() ) {
280 $wgOut->addWikiText( wfMsg( 'talkpagetext' ) );
281 }
282
283 # Attempt submission here. This will check for edit conflicts,
284 # and redundantly check for locked database, blocked IPs, etc.
285 # that edit() already checked just in case someone tries to sneak
286 # in the back door with a hand-edited submission URL.
287
288 if ( 'save' == $this->formtype ) {
289 if ( !$this->attemptSave() ) {
290 wfProfileOut( "$fname-business-end" );
291 wfProfileOut( $fname );
292 return;
293 }
294 }
295
296 # First time through: get contents, set time for conflict
297 # checking, etc.
298 if ( 'initial' == $this->formtype || $this->firsttime ) {
299 $this->initialiseForm();
300 }
301
302 $this->showEditForm();
303 wfProfileOut( "$fname-business-end" );
304 wfProfileOut( $fname );
305 }
306
307 /**
308 * Return true if this page should be previewed when the edit form
309 * is initially opened.
310 * @return bool
311 * @access private
312 */
313 function previewOnOpen() {
314 global $wgUser;
315 return $this->section != 'new' &&
316 ( ( $wgUser->getOption( 'previewonfirst' ) && $this->mTitle->exists() ) ||
317 ( $this->mTitle->getNamespace() == NS_CATEGORY &&
318 !$this->mTitle->exists() ) );
319 }
320
321 /**
322 * @todo document
323 */
324 function importFormData( &$request ) {
325 global $wgLang ;
326 $fname = 'EditPage::importFormData';
327 wfProfileIn( $fname );
328
329 if( $request->wasPosted() ) {
330 # These fields need to be checked for encoding.
331 # Also remove trailing whitespace, but don't remove _initial_
332 # whitespace from the text boxes. This may be significant formatting.
333 $this->textbox1 = $this->safeUnicodeInput( $request, 'wpTextbox1' );
334 $this->textbox2 = $this->safeUnicodeInput( $request, 'wpTextbox2' );
335 $this->mMetaData = rtrim( $request->getText( 'metadata' ) );
336 # Truncate for whole multibyte characters. +5 bytes for ellipsis
337 $this->summary = $wgLang->truncate( $request->getText( 'wpSummary' ), 250 );
338
339 $this->edittime = $request->getVal( 'wpEdittime' );
340 $this->starttime = $request->getVal( 'wpStarttime' );
341
342 $this->scrolltop = $request->getIntOrNull( 'wpScrolltop' );
343
344 if( is_null( $this->edittime ) ) {
345 # If the form is incomplete, force to preview.
346 wfDebug( "$fname: Form data appears to be incomplete\n" );
347 wfDebug( "POST DATA: " . var_export( $_POST, true ) . "\n" );
348 $this->preview = true;
349 } else {
350 /* Fallback for live preview */
351 $this->preview = $request->getCheck( 'wpPreview' ) || $request->getCheck( 'wpLivePreview' );
352 $this->diff = $request->getCheck( 'wpDiff' );
353
354 if( !$this->preview ) {
355 if ( $this->tokenOk( $request ) ) {
356 # Some browsers will not report any submit button
357 # if the user hits enter in the comment box.
358 # The unmarked state will be assumed to be a save,
359 # if the form seems otherwise complete.
360 wfDebug( "$fname: Passed token check.\n" );
361 } else {
362 # Page might be a hack attempt posted from
363 # an external site. Preview instead of saving.
364 wfDebug( "$fname: Failed token check; forcing preview\n" );
365 $this->preview = true;
366 }
367 }
368 }
369 $this->save = ! ( $this->preview OR $this->diff );
370 if( !preg_match( '/^\d{14}$/', $this->edittime )) {
371 $this->edittime = null;
372 }
373
374 if( !preg_match( '/^\d{14}$/', $this->starttime )) {
375 $this->starttime = null;
376 }
377
378 $this->recreate = $request->getCheck( 'wpRecreate' );
379
380 $this->minoredit = $request->getCheck( 'wpMinoredit' );
381 $this->watchthis = $request->getCheck( 'wpWatchthis' );
382 } else {
383 # Not a posted form? Start with nothing.
384 wfDebug( "$fname: Not a posted form.\n" );
385 $this->textbox1 = '';
386 $this->textbox2 = '';
387 $this->mMetaData = '';
388 $this->summary = '';
389 $this->edittime = '';
390 $this->starttime = wfTimestampNow();
391 $this->preview = false;
392 $this->save = false;
393 $this->diff = false;
394 $this->minoredit = false;
395 $this->watchthis = false;
396 $this->recreate = false;
397 }
398
399 $this->oldid = $request->getInt( 'oldid' );
400
401 # Section edit can come from either the form or a link
402 $this->section = $request->getVal( 'wpSection', $request->getVal( 'section' ) );
403
404 $this->live = $request->getCheck( 'live' );
405 $this->editintro = $request->getText( 'editintro' );
406
407 wfProfileOut( $fname );
408 }
409
410 /**
411 * Make sure the form isn't faking a user's credentials.
412 *
413 * @param WebRequest $request
414 * @return bool
415 * @access private
416 */
417 function tokenOk( &$request ) {
418 global $wgUser;
419 if( $wgUser->isAnon() ) {
420 # Anonymous users may not have a session
421 # open. Don't tokenize.
422 $this->mTokenOk = true;
423 } else {
424 $this->mTokenOk = $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
425 }
426 return $this->mTokenOk;
427 }
428
429 function showIntro() {
430 global $wgOut, $wgUser;
431 $addstandardintro=true;
432 if($this->editintro) {
433 $introtitle=Title::newFromText($this->editintro);
434 if(isset($introtitle) && $introtitle->userCanRead()) {
435 $rev=Revision::newFromTitle($introtitle);
436 if($rev) {
437 $wgOut->addSecondaryWikiText($rev->getText());
438 $addstandardintro=false;
439 }
440 }
441 }
442 if($addstandardintro) {
443 if ( $wgUser->isLoggedIn() )
444 $wgOut->addWikiText( wfMsg( 'newarticletext' ) );
445 else
446 $wgOut->addWikiText( wfMsg( 'newarticletextanon' ) );
447 }
448 }
449
450 /**
451 * Attempt submission
452 * @return bool false if output is done, true if the rest of the form should be displayed
453 */
454 function attemptSave() {
455 global $wgSpamRegex, $wgFilterCallback, $wgUser, $wgOut;
456 global $wgMaxArticleSize;
457
458 $fname = 'EditPage::attemptSave';
459 wfProfileIn( $fname );
460 wfProfileIn( "$fname-checks" );
461
462 # Reintegrate metadata
463 if ( $this->mMetaData != '' ) $this->textbox1 .= "\n" . $this->mMetaData ;
464 $this->mMetaData = '' ;
465
466 # Check for spam
467 if ( $wgSpamRegex && preg_match( $wgSpamRegex, $this->textbox1, $matches ) ) {
468 $this->spamPage ( $matches[0] );
469 wfProfileOut( "$fname-checks" );
470 wfProfileOut( $fname );
471 return false;
472 }
473 if ( $wgFilterCallback && $wgFilterCallback( $this->mTitle, $this->textbox1, $this->section ) ) {
474 # Error messages or other handling should be performed by the filter function
475 wfProfileOut( $fname );
476 wfProfileOut( "$fname-checks" );
477 return false;
478 }
479 if ( !wfRunHooks( 'EditFilter', array( &$this, $this->textbox1, $this->section ) ) ) {
480 # Error messages or other handling should be performed by the filter function
481 wfProfileOut( $fname );
482 wfProfileOut( "$fname-checks" );
483 return false;
484 }
485 if ( $wgUser->isBlockedFrom( $this->mTitle, false ) ) {
486 # Check block state against master, thus 'false'.
487 $this->blockedIPpage();
488 wfProfileOut( "$fname-checks" );
489 wfProfileOut( $fname );
490 return false;
491 }
492 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
493 if ( $this->kblength > $wgMaxArticleSize ) {
494 // Error will be displayed by showEditForm()
495 $this->tooBig = true;
496 wfProfileOut( "$fname-checks" );
497 wfProfileOut( $fname );
498 return true;
499 }
500
501 if ( !$wgUser->isAllowed('edit') ) {
502 if ( $wgUser->isAnon() ) {
503 $this->userNotLoggedInPage();
504 wfProfileOut( "$fname-checks" );
505 wfProfileOut( $fname );
506 return false;
507 }
508 else {
509 $wgOut->readOnlyPage();
510 wfProfileOut( "$fname-checks" );
511 wfProfileOut( $fname );
512 return false;
513 }
514 }
515
516 if ( wfReadOnly() ) {
517 $wgOut->readOnlyPage();
518 wfProfileOut( "$fname-checks" );
519 wfProfileOut( $fname );
520 return false;
521 }
522 if ( $wgUser->pingLimiter() ) {
523 $wgOut->rateLimited();
524 wfProfileOut( "$fname-checks" );
525 wfProfileOut( $fname );
526 return false;
527 }
528
529 # If the article has been deleted while editing, don't save it without
530 # confirmation
531 if ( $this->deletedSinceEdit && !$this->recreate ) {
532 wfProfileOut( "$fname-checks" );
533 wfProfileOut( $fname );
534 return true;
535 }
536
537 wfProfileOut( "$fname-checks" );
538
539 # If article is new, insert it.
540 $aid = $this->mTitle->getArticleID( GAID_FOR_UPDATE );
541 if ( 0 == $aid ) {
542 // Late check for create permission, just in case *PARANOIA*
543 if ( !$this->mTitle->userCan( 'create' ) ) {
544 wfDebug( "$fname: no create permission\n" );
545 $this->noCreatePermission();
546 wfProfileOut( $fname );
547 return;
548 }
549
550 # Don't save a new article if it's blank.
551 if ( ( '' == $this->textbox1 ) ) {
552 $wgOut->redirect( $this->mTitle->getFullURL() );
553 wfProfileOut( $fname );
554 return false;
555 }
556
557 $isComment=($this->section=='new');
558 $this->mArticle->insertNewArticle( $this->textbox1, $this->summary,
559 $this->minoredit, $this->watchthis, false, $isComment);
560
561 wfProfileOut( $fname );
562 return false;
563 }
564
565 # Article exists. Check for edit conflict.
566
567 $this->mArticle->clear(); # Force reload of dates, etc.
568 $this->mArticle->forUpdate( true ); # Lock the article
569
570 if( $this->mArticle->getTimestamp() != $this->edittime ) {
571 $this->isConflict = true;
572 if( $this->section == 'new' ) {
573 if( $this->mArticle->getUserText() == $wgUser->getName() &&
574 $this->mArticle->getComment() == $this->summary ) {
575 // Probably a duplicate submission of a new comment.
576 // This can happen when squid resends a request after
577 // a timeout but the first one actually went through.
578 wfDebug( "EditPage::editForm duplicate new section submission; trigger edit conflict!\n" );
579 } else {
580 // New comment; suppress conflict.
581 $this->isConflict = false;
582 wfDebug( "EditPage::editForm conflict suppressed; new section\n" );
583 }
584 }
585 }
586 $userid = $wgUser->getID();
587
588 if ( $this->isConflict) {
589 wfDebug( "EditPage::editForm conflict! getting section '$this->section' for time '$this->edittime' (article time '" .
590 $this->mArticle->getTimestamp() . "'\n" );
591 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary, $this->edittime);
592 }
593 else {
594 wfDebug( "EditPage::editForm getting section '$this->section'\n" );
595 $text = $this->mArticle->replaceSection( $this->section, $this->textbox1, $this->summary);
596 }
597 if( is_null( $text ) ) {
598 wfDebug( "EditPage::editForm activating conflict; section replace failed.\n" );
599 $this->isConflict = true;
600 $text = $this->textbox1;
601 }
602
603 # Suppress edit conflict with self, except for section edits where merging is required.
604 if ( ( $this->section == '' ) && ( 0 != $userid ) && ( $this->mArticle->getUser() == $userid ) ) {
605 wfDebug( "Suppressing edit conflict, same user.\n" );
606 $this->isConflict = false;
607 } else {
608 # switch from section editing to normal editing in edit conflict
609 if($this->isConflict) {
610 # Attempt merge
611 if( $this->mergeChangesInto( $text ) ){
612 // Successful merge! Maybe we should tell the user the good news?
613 $this->isConflict = false;
614 wfDebug( "Suppressing edit conflict, successful merge.\n" );
615 } else {
616 $this->section = '';
617 $this->textbox1 = $text;
618 wfDebug( "Keeping edit conflict, failed merge.\n" );
619 }
620 }
621 }
622
623 if ( $this->isConflict ) {
624 wfProfileOut( $fname );
625 return true;
626 }
627
628 # All's well
629 wfProfileIn( "$fname-sectionanchor" );
630 $sectionanchor = '';
631 if( $this->section == 'new' ) {
632 if( $this->summary != '' ) {
633 $sectionanchor = $this->sectionAnchor( $this->summary );
634 }
635 } elseif( $this->section != '' ) {
636 # Try to get a section anchor from the section source, redirect to edited section if header found
637 # XXX: might be better to integrate this into Article::replaceSection
638 # for duplicate heading checking and maybe parsing
639 $hasmatch = preg_match( "/^ *([=]{1,6})(.*?)(\\1) *\\n/i", $this->textbox1, $matches );
640 # we can't deal with anchors, includes, html etc in the header for now,
641 # headline would need to be parsed to improve this
642 if($hasmatch and strlen($matches[2]) > 0) {
643 $sectionanchor = $this->sectionAnchor( $matches[2] );
644 }
645 }
646 wfProfileOut( "$fname-sectionanchor" );
647
648 // Save errors may fall down to the edit form, but we've now
649 // merged the section into full text. Clear the section field
650 // so that later submission of conflict forms won't try to
651 // replace that into a duplicated mess.
652 $this->textbox1 = $text;
653 $this->section = '';
654
655 // Check for length errors again now that the section is merged in
656 $this->kblength = (int)(strlen( $text ) / 1024);
657 if ( $this->kblength > $wgMaxArticleSize ) {
658 $this->tooBig = true;
659 wfProfileOut( $fname );
660 return true;
661 }
662
663 # update the article here
664 if( $this->mArticle->updateArticle( $text, $this->summary, $this->minoredit,
665 $this->watchthis, '', $sectionanchor ) ) {
666 wfProfileOut( $fname );
667 return false;
668 } else {
669 $this->isConflict = true;
670 }
671 wfProfileOut( $fname );
672 return true;
673 }
674
675 /**
676 * Initialise form fields in the object
677 * Called on the first invocation, e.g. when a user clicks an edit link
678 */
679 function initialiseForm() {
680 $this->edittime = $this->mArticle->getTimestamp();
681 $this->textbox1 = $this->mArticle->getContent();
682 $this->summary = '';
683 if ( !$this->mArticle->exists() && $this->mArticle->mTitle->getNamespace() == NS_MEDIAWIKI )
684 $this->textbox1 = wfMsgWeirdKey ( $this->mArticle->mTitle->getText() ) ;
685 wfProxyCheck();
686 }
687
688 /**
689 * Send the edit form and related headers to $wgOut
690 * @param $formCallback Optional callable that takes an OutputPage
691 * parameter; will be called during form output
692 * near the top, for captchas and the like.
693 */
694 function showEditForm( $formCallback=null ) {
695 global $wgOut, $wgUser, $wgLang, $wgContLang, $wgMaxArticleSize;
696
697 $fname = 'EditPage::showEditForm';
698 wfProfileIn( $fname );
699
700 $sk =& $wgUser->getSkin();
701
702 wfRunHooks( 'EditPage::showEditForm:initial', array( &$this ) ) ;
703
704 $wgOut->setRobotpolicy( 'noindex,nofollow' );
705
706 # Enabled article-related sidebar, toplinks, etc.
707 $wgOut->setArticleRelated( true );
708
709 if ( $this->isConflict ) {
710 $s = wfMsg( 'editconflict', $this->mTitle->getPrefixedText() );
711 $wgOut->setPageTitle( $s );
712 $wgOut->addWikiText( wfMsg( 'explainconflict' ) );
713
714 $this->textbox2 = $this->textbox1;
715 $this->textbox1 = $this->mArticle->getContent();
716 $this->edittime = $this->mArticle->getTimestamp();
717 } else {
718
719 if( $this->section != '' ) {
720 if( $this->section == 'new' ) {
721 $s = wfMsg('editingcomment', $this->mTitle->getPrefixedText() );
722 } else {
723 $s = wfMsg('editingsection', $this->mTitle->getPrefixedText() );
724 if( !$this->preview && !$this->diff ) {
725 preg_match( "/^(=+)(.+)\\1/mi",
726 $this->textbox1,
727 $matches );
728 if( !empty( $matches[2] ) ) {
729 $this->summary = "/* ". trim($matches[2])." */ ";
730 }
731 }
732 }
733 } else {
734 $s = wfMsg( 'editing', $this->mTitle->getPrefixedText() );
735 }
736 $wgOut->setPageTitle( $s );
737 if ( !$this->checkUnicodeCompliantBrowser() ) {
738 $wgOut->addWikiText( wfMsg( 'nonunicodebrowser') );
739 }
740 if ( isset( $this->mArticle )
741 && isset( $this->mArticle->mRevision )
742 && !$this->mArticle->mRevision->isCurrent() ) {
743 $this->mArticle->setOldSubtitle( $this->mArticle->mRevision->getId() );
744 $wgOut->addWikiText( wfMsg( 'editingold' ) );
745 }
746 }
747
748 if( wfReadOnly() ) {
749 $wgOut->addWikiText( wfMsg( 'readonlywarning' ) );
750 } else if ( $this->isCssJsSubpage and 'preview' != $this->formtype) {
751 $wgOut->addWikiText( wfMsg( 'usercssjsyoucanpreview' ));
752 } else if( $wgUser->isAnon() && $this->formtype != 'preview' ) {
753 $wgOut->addWikiText( wfMsg( 'anoneditwarning' ) );
754 }
755
756 if( $this->mTitle->isProtected( 'edit' ) ) {
757 if( $this->mTitle->isSemiProtected() ) {
758 $notice = wfMsg( 'semiprotectedpagewarning' );
759 if( wfEmptyMsg( 'semiprotectedpagewarning', $notice ) || $notice == '-' ) {
760 $notice = '';
761 }
762 } else {
763 $notice = wfMsg( 'protectedpagewarning' );
764 }
765 $wgOut->addWikiText( $notice );
766 }
767
768 if ( $this->kblength === false ) {
769 $this->kblength = (int)(strlen( $this->textbox1 ) / 1024);
770 }
771 if ( $this->tooBig || $this->kblength > $wgMaxArticleSize ) {
772 $wgOut->addWikiText( wfMsg( 'longpageerror', $wgLang->formatNum( $this->kblength ), $wgMaxArticleSize ) );
773 } elseif( $this->kblength > 29 ) {
774 $wgOut->addWikiText( wfMsg( 'longpagewarning', $wgLang->formatNum( $this->kblength ) ) );
775 }
776
777 $rows = $wgUser->getOption( 'rows' );
778 $cols = $wgUser->getOption( 'cols' );
779
780 $ew = $wgUser->getOption( 'editwidth' );
781 if ( $ew ) $ew = " style=\"width:100%\"";
782 else $ew = '';
783
784 $q = 'action=submit';
785 #if ( "no" == $redirect ) { $q .= "&redirect=no"; }
786 $action = $this->mTitle->escapeLocalURL( $q );
787
788 $summary = wfMsg('summary');
789 $subject = wfMsg('subject');
790 $minor = wfMsg('minoredit');
791 $watchthis = wfMsg ('watchthis');
792
793 $cancel = $sk->makeKnownLink( $this->mTitle->getPrefixedText(),
794 wfMsg('cancel') );
795 $edithelpurl = $sk->makeInternalOrExternalUrl( wfMsg( 'edithelppage' ));
796 $edithelp = '<a target="helpwindow" href="'.$edithelpurl.'">'.
797 htmlspecialchars( wfMsg( 'edithelp' ) ).'</a> '.
798 htmlspecialchars( wfMsg( 'newwindow' ) );
799
800 global $wgRightsText;
801 $copywarn = "<div id=\"editpage-copywarn\">\n" .
802 wfMsg( $wgRightsText ? 'copyrightwarning' : 'copyrightwarning2',
803 '[[' . wfMsgForContent( 'copyrightpage' ) . ']]',
804 $wgRightsText ) . "\n</div>";
805
806 if( $wgUser->getOption('showtoolbar') and !$this->isCssJsSubpage ) {
807 # prepare toolbar for edit buttons
808 $toolbar = $this->getEditToolbar();
809 } else {
810 $toolbar = '';
811 }
812
813 // activate checkboxes if user wants them to be always active
814 if( !$this->preview && !$this->diff ) {
815 if( $wgUser->getOption( 'watchdefault' ) ) $this->watchthis = true;
816 if( $wgUser->getOption( 'minordefault' ) ) $this->minoredit = true;
817
818 // activate checkbox also if user is already watching the page,
819 // require wpWatchthis to be unset so that second condition is not
820 // checked unnecessarily
821 if( !$this->watchthis && $this->mTitle->userIsWatching() ) $this->watchthis = true;
822 }
823
824 $minoredithtml = '';
825
826 if ( $wgUser->isAllowed('minoredit') ) {
827 $minoredithtml =
828 "<input tabindex='3' type='checkbox' value='1' name='wpMinoredit'".($this->minoredit?" checked='checked'":"").
829 " accesskey='".wfMsg('accesskey-minoredit')."' id='wpMinoredit' />".
830 "<label for='wpMinoredit' title='".wfMsg('tooltip-minoredit')."'>{$minor}</label>";
831 }
832
833 $watchhtml = '';
834
835 if ( $wgUser->isLoggedIn() ) {
836 $watchhtml = "<input tabindex='4' type='checkbox' name='wpWatchthis'".
837 ($this->watchthis?" checked='checked'":"").
838 " accesskey=\"".htmlspecialchars(wfMsg('accesskey-watch'))."\" id='wpWatchthis' />".
839 "<label for='wpWatchthis' title=\"" .
840 htmlspecialchars(wfMsg('tooltip-watch'))."\">{$watchthis}</label>";
841 }
842
843 $checkboxhtml = $minoredithtml . $watchhtml;
844
845 if ( $wgUser->getOption( 'previewontop' ) ) {
846
847 if ( 'preview' == $this->formtype ) {
848 $this->showPreview();
849 } else {
850 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
851 }
852
853 if ( 'diff' == $this->formtype ) {
854 $wgOut->addHTML( $this->getDiff() );
855 }
856 }
857
858
859 # if this is a comment, show a subject line at the top, which is also the edit summary.
860 # Otherwise, show a summary field at the bottom
861 $summarytext = htmlspecialchars( $wgContLang->recodeForEdit( $this->summary ) ); # FIXME
862 if( $this->section == 'new' ) {
863 $commentsubject="<span id='wpSummaryLabel'><label for='wpSummary'>{$subject}:</label></span> <div class='editOptions'><input tabindex='1' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
864 $editsummary = '';
865 } else {
866 $commentsubject = '';
867 $editsummary="<span id='wpSummaryLabel'><label for='wpSummary'>{$summary}:</label></span> <div class='editOptions'><input tabindex='2' type='text' value=\"$summarytext\" name='wpSummary' id='wpSummary' maxlength='200' size='60' /><br />";
868 }
869
870 # Set focus to the edit box on load, except on preview or diff, where it would interfere with the display
871 if( !$this->preview && !$this->diff ) {
872 $wgOut->setOnloadHandler( 'document.editform.wpTextbox1.focus()' );
873 }
874 $templates = $this->formatTemplates();
875
876 global $wgUseMetadataEdit ;
877 if ( $wgUseMetadataEdit ) {
878 $metadata = $this->mMetaData ;
879 $metadata = htmlspecialchars( $wgContLang->recodeForEdit( $metadata ) ) ;
880 $helppage = Title::newFromText( wfMsg( "metadata_page" ) ) ;
881 $top = wfMsg( 'metadata', $helppage->getLocalURL() );
882 $metadata = $top . "<textarea name='metadata' rows='3' cols='{$cols}'{$ew}>{$metadata}</textarea>" ;
883 }
884 else $metadata = "" ;
885
886 $hidden = '';
887 $recreate = '';
888 if ($this->deletedSinceEdit) {
889 if ( 'save' != $this->formtype ) {
890 $wgOut->addWikiText( wfMsg('deletedwhileediting'));
891 } else {
892 // Hide the toolbar and edit area, use can click preview to get it back
893 // Add an confirmation checkbox and explanation.
894 $toolbar = '';
895 $hidden = 'type="hidden" style="display:none;"';
896 $recreate = $wgOut->parse( wfMsg( 'confirmrecreate', $this->lastDelete->user_name , $this->lastDelete->log_comment ));
897 $recreate .=
898 "<br /><input tabindex='1' type='checkbox' value='1' name='wpRecreate' id='wpRecreate' />".
899 "<label for='wpRecreate' title='".wfMsg('tooltip-recreate')."'>". wfMsg('recreate')."</label>";
900 }
901 }
902
903 $temp = array(
904 'id' => 'wpSave',
905 'name' => 'wpSave',
906 'type' => 'submit',
907 'tabindex' => '5',
908 'value' => wfMsg('savearticle'),
909 'accesskey' => wfMsg('accesskey-save'),
910 'title' => wfMsg('tooltip-save'),
911 );
912 $buttons['save'] = wfElement('input', $temp, '');
913 $temp = array(
914 'id' => 'wpDiff',
915 'name' => 'wpDiff',
916 'type' => 'submit',
917 'tabindex' => '7',
918 'value' => wfMsg('showdiff'),
919 'accesskey' => wfMsg('accesskey-diff'),
920 'title' => wfMsg('tooltip-diff'),
921 );
922 $buttons['diff'] = wfElement('input', $temp, '');
923
924 global $wgLivePreview;
925 if ( $wgLivePreview ) {
926 $temp = array(
927 'id' => 'wpPreview',
928 'name' => 'wpPreview',
929 'type' => 'submit',
930 'tabindex' => '6',
931 'value' => wfMsg('showpreview'),
932 'accesskey' => '',
933 'title' => wfMsg('tooltip-preview'),
934 'style' => 'display: none;',
935 );
936 $buttons['preview'] = wfElement('input', $temp, '');
937 $temp = array(
938 'id' => 'wpLivePreview',
939 'name' => 'wpLivePreview',
940 'type' => 'submit',
941 'tabindex' => '6',
942 'value' => wfMsg('showlivepreview'),
943 'accesskey' => wfMsg('accesskey-preview'),
944 'title' => '',
945 'onclick' => $this->doLivePreviewScript(),
946 );
947 $buttons['live'] = wfElement('input', $temp, '');
948 } else {
949 $temp = array(
950 'id' => 'wpPreview',
951 'name' => 'wpPreview',
952 'type' => 'submit',
953 'tabindex' => '6',
954 'value' => wfMsg('showpreview'),
955 'accesskey' => wfMsg('accesskey-preview'),
956 'title' => wfMsg('tooltip-preview'),
957 );
958 $buttons['preview'] = wfElement('input', $temp, '');
959 $buttons['live'] = '';
960 }
961
962 $safemodehtml = $this->checkUnicodeCompliantBrowser()
963 ? ""
964 : "<input type='hidden' name=\"safemode\" value='1' />\n";
965
966 $wgOut->addHTML( <<<END
967 {$toolbar}
968 <form id="editform" name="editform" method="post" action="$action"
969 enctype="multipart/form-data">
970 END
971 );
972
973 if( is_callable( $formCallback ) ) {
974 call_user_func_array( $formCallback, array( &$wgOut ) );
975 }
976
977 // Put these up at the top to ensure they aren't lost on early form submission
978 $wgOut->addHTML( "
979 <input type='hidden' value=\"" . htmlspecialchars( $this->section ) . "\" name=\"wpSection\" />
980 <input type='hidden' value=\"{$this->starttime}\" name=\"wpStarttime\" />\n
981 <input type='hidden' value=\"{$this->edittime}\" name=\"wpEdittime\" />\n
982 <input type='hidden' value=\"{$this->scrolltop}\" name=\"wpScrolltop\" id=\"wpScrolltop\" />\n" );
983
984 $wgOut->addHTML( <<<END
985 $recreate
986 {$commentsubject}
987 <textarea tabindex='1' accesskey="," name="wpTextbox1" id="wpTextbox1" rows='{$rows}'
988 cols='{$cols}'{$ew} $hidden>
989 END
990 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox1 ) ) .
991 "
992 </textarea>
993 " );
994
995 $wgOut->addWikiText( $copywarn );
996 $wgOut->addHTML( "
997 {$metadata}
998 {$editsummary}
999 {$checkboxhtml}
1000 {$safemodehtml}
1001 ");
1002
1003 $wgOut->addHTML("
1004 <div class='editButtons'>
1005 {$buttons['save']}
1006 {$buttons['preview']}
1007 {$buttons['live']}
1008 {$buttons['diff']}
1009 <span class='editHelp'>{$cancel} | {$edithelp}</span>
1010 </div><!-- editButtons -->
1011 </div><!-- editOptions -->");
1012
1013 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1014
1015 $wgOut->addHTML( "
1016 <div class='templatesUsed'>
1017 {$templates}
1018 </div>
1019 " );
1020
1021 if ( $wgUser->isLoggedIn() ) {
1022 /**
1023 * To make it harder for someone to slip a user a page
1024 * which submits an edit form to the wiki without their
1025 * knowledge, a random token is associated with the login
1026 * session. If it's not passed back with the submission,
1027 * we won't save the page, or render user JavaScript and
1028 * CSS previews.
1029 */
1030 $token = htmlspecialchars( $wgUser->editToken() );
1031 $wgOut->addHTML( "\n<input type='hidden' value=\"$token\" name=\"wpEditToken\" />\n" );
1032 }
1033
1034
1035 if ( $this->isConflict ) {
1036 require_once( "DifferenceEngine.php" );
1037 $wgOut->addWikiText( '==' . wfMsg( "yourdiff" ) . '==' );
1038
1039 $de = new DifferenceEngine( $this->mTitle );
1040 $de->setText( $this->textbox2, $this->textbox1 );
1041 $de->showDiff( wfMsg( "yourtext" ), wfMsg( "storedversion" ) );
1042
1043 $wgOut->addWikiText( '==' . wfMsg( "yourtext" ) . '==' );
1044 $wgOut->addHTML( "<textarea tabindex=6 id='wpTextbox2' name=\"wpTextbox2\" rows='{$rows}' cols='{$cols}' wrap='virtual'>"
1045 . htmlspecialchars( $this->safeUnicodeOutput( $this->textbox2 ) ) . "\n</textarea>" );
1046 }
1047 $wgOut->addHTML( "</form>\n" );
1048 if ( !$wgUser->getOption( 'previewontop' ) ) {
1049
1050 if ( $this->formtype == 'preview') {
1051 $this->showPreview();
1052 } else {
1053 $wgOut->addHTML( '<div id="wikiPreview"></div>' );
1054 }
1055
1056 if ( $this->formtype == 'diff') {
1057 $wgOut->addHTML( $this->getDiff() );
1058 }
1059
1060 }
1061
1062 wfProfileOut( $fname );
1063 }
1064
1065 /**
1066 * Append preview output to $wgOut.
1067 * Includes category rendering if this is a category page.
1068 * @access private
1069 */
1070 function showPreview() {
1071 global $wgOut;
1072 $wgOut->addHTML( '<div id="wikiPreview">' );
1073 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1074 $this->mArticle->openShowCategory();
1075 }
1076 $previewOutput = $this->getPreviewText();
1077 $wgOut->addHTML( $previewOutput );
1078 if($this->mTitle->getNamespace() == NS_CATEGORY) {
1079 $this->mArticle->closeShowCategory();
1080 }
1081 $wgOut->addHTML( "<br style=\"clear:both;\" />\n" );
1082 $wgOut->addHTML( '</div>' );
1083 }
1084
1085 /**
1086 * Prepare a list of templates used by this page. Returns HTML.
1087 */
1088 function formatTemplates() {
1089 global $wgUser;
1090
1091 $fname = 'EditPage::formatTemplates';
1092 wfProfileIn( $fname );
1093
1094 $sk =& $wgUser->getSkin();
1095
1096 $outText = '';
1097 $templates = $this->mArticle->getUsedTemplates();
1098 if ( count( $templates ) > 0 ) {
1099 # Do a batch existence check
1100 $batch = new LinkBatch;
1101 foreach( $templates as $title ) {
1102 $batch->addObj( $title );
1103 }
1104 $batch->execute();
1105
1106 # Construct the HTML
1107 $outText = '<br />'. wfMsg( 'templatesused' ) . '<ul>';
1108 foreach ( $templates as $titleObj ) {
1109 $outText .= '<li>' . $sk->makeLinkObj( $titleObj ) . '</li>';
1110 }
1111 $outText .= '</ul>';
1112 }
1113 wfProfileOut( $fname );
1114 return $outText;
1115 }
1116
1117 /**
1118 * Live Preview lets us fetch rendered preview page content and
1119 * add it to the page without refreshing the whole page.
1120 * If not supported by the browser it will fall through to the normal form
1121 * submission method.
1122 *
1123 * This function outputs a script tag to support live preview, and
1124 * returns an onclick handler which should be added to the attributes
1125 * of the preview button
1126 */
1127 function doLivePreviewScript() {
1128 global $wgStylePath, $wgJsMimeType, $wgOut, $wgTitle;
1129 $wgOut->addHTML( '<script type="'.$wgJsMimeType.'" src="' .
1130 htmlspecialchars( $wgStylePath . '/common/preview.js' ) .
1131 '"></script>' . "\n" );
1132 $liveAction = $wgTitle->getLocalUrl( 'action=submit&wpPreview=true&live=true' );
1133 return "return !livePreview(" .
1134 "getElementById('wikiPreview')," .
1135 "editform.wpTextbox1.value," .
1136 '"' . $liveAction . '"' . ")";
1137 }
1138
1139 function getLastDelete() {
1140 $dbr =& wfGetDB( DB_SLAVE );
1141 $fname = 'EditPage::getLastDelete';
1142 $res = $dbr->select(
1143 array( 'logging', 'user' ),
1144 array( 'log_type',
1145 'log_action',
1146 'log_timestamp',
1147 'log_user',
1148 'log_namespace',
1149 'log_title',
1150 'log_comment',
1151 'log_params',
1152 'user_name', ),
1153 array( 'log_namespace' => $this->mTitle->getNamespace(),
1154 'log_title' => $this->mTitle->getDBkey(),
1155 'log_type' => 'delete',
1156 'log_action' => 'delete',
1157 'user_id=log_user' ),
1158 $fname,
1159 array( 'LIMIT' => 1, 'ORDER BY' => 'log_timestamp DESC' ) );
1160
1161 if($dbr->numRows($res) == 1) {
1162 while ( $x = $dbr->fetchObject ( $res ) )
1163 $data = $x;
1164 $dbr->freeResult ( $res ) ;
1165 } else {
1166 $data = null;
1167 }
1168 return $data;
1169 }
1170
1171 /**
1172 * @todo document
1173 */
1174 function getPreviewText() {
1175 global $wgOut, $wgUser, $wgTitle, $wgParser;
1176
1177 $fname = 'EditPage::getPreviewText';
1178 wfProfileIn( $fname );
1179
1180 if ( $this->mTokenOk ) {
1181 $msg = 'previewnote';
1182 } else {
1183 $msg = 'session_fail_preview';
1184 }
1185 $previewhead = '<h2>' . htmlspecialchars( wfMsg( 'preview' ) ) . "</h2>\n" .
1186 "<div class='previewnote'>" . $wgOut->parse( wfMsg( $msg ) ) . "</div>\n";
1187 if ( $this->isConflict ) {
1188 $previewhead.='<h2>' . htmlspecialchars( wfMsg( 'previewconflict' ) ) . "</h2>\n";
1189 }
1190
1191 $parserOptions = ParserOptions::newFromUser( $wgUser );
1192 $parserOptions->setEditSection( false );
1193
1194 # don't parse user css/js, show message about preview
1195 # XXX: stupid php bug won't let us use $wgTitle->isCssJsSubpage() here
1196
1197 if ( $this->isCssJsSubpage ) {
1198 if(preg_match("/\\.css$/", $wgTitle->getText() ) ) {
1199 $previewtext = wfMsg('usercsspreview');
1200 } else if(preg_match("/\\.js$/", $wgTitle->getText() ) ) {
1201 $previewtext = wfMsg('userjspreview');
1202 }
1203 $parserOptions->setTidy(true);
1204 $parserOutput = $wgParser->parse( $previewtext , $wgTitle, $parserOptions );
1205 $wgOut->addHTML( $parserOutput->mText );
1206 wfProfileOut( $fname );
1207 return $previewhead;
1208 } else {
1209 # if user want to see preview when he edit an article
1210 if( $wgUser->getOption('previewonfirst') and ($this->textbox1 == '')) {
1211 $this->textbox1 = $this->mArticle->getContent();
1212 }
1213
1214 $toparse = $this->textbox1;
1215
1216 # If we're adding a comment, we need to show the
1217 # summary as the headline
1218 if($this->section=="new" && $this->summary!="") {
1219 $toparse="== {$this->summary} ==\n\n".$toparse;
1220 }
1221
1222 if ( $this->mMetaData != "" ) $toparse .= "\n" . $this->mMetaData ;
1223 $parserOptions->setTidy(true);
1224 $parserOutput = $wgParser->parse( $this->mArticle->preSaveTransform( $toparse ) ."\n\n",
1225 $wgTitle, $parserOptions );
1226
1227 $previewHTML = $parserOutput->getText();
1228 $wgOut->addParserOutputNoText( $parserOutput );
1229
1230 wfProfileOut( $fname );
1231 return $previewhead . $previewHTML;
1232 }
1233 }
1234
1235 /**
1236 * @todo document
1237 */
1238 function blockedIPpage() {
1239 global $wgOut;
1240 $wgOut->blockedPage();
1241 }
1242
1243 /**
1244 * @todo document
1245 */
1246 function userNotLoggedInPage() {
1247 global $wgOut;
1248
1249 $wgOut->setPageTitle( wfMsg( 'whitelistedittitle' ) );
1250 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1251 $wgOut->setArticleRelated( false );
1252
1253 $wgOut->addWikiText( wfMsg( 'whitelistedittext' ) );
1254 $wgOut->returnToMain( false );
1255 }
1256
1257 /**
1258 * Creates a basic error page which informs the user that
1259 * they have to validate their email address before being
1260 * allowed to edit.
1261 */
1262 function userNotConfirmedPage() {
1263
1264 global $wgOut;
1265
1266 $wgOut->setPageTitle( wfMsg( 'confirmedittitle' ) );
1267 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1268 $wgOut->setArticleRelated( false );
1269 $wgOut->addWikiText( wfMsg( 'confirmedittext' ) );
1270 $wgOut->returnToMain( false );
1271 }
1272
1273 /**
1274 * @todo document
1275 */
1276 function spamPage ( $match = false )
1277 {
1278 global $wgOut;
1279 $wgOut->setPageTitle( wfMsg( 'spamprotectiontitle' ) );
1280 $wgOut->setRobotpolicy( 'noindex,nofollow' );
1281 $wgOut->setArticleRelated( false );
1282
1283 $wgOut->addWikiText( wfMsg( 'spamprotectiontext' ) );
1284 if ( $match ) {
1285 $wgOut->addWikiText( wfMsg( 'spamprotectionmatch', "<nowiki>{$match}</nowiki>" ) );
1286 }
1287 $wgOut->returnToMain( false );
1288 }
1289
1290 /**
1291 * @access private
1292 * @todo document
1293 */
1294 function mergeChangesInto( &$editText ){
1295 $fname = 'EditPage::mergeChangesInto';
1296 wfProfileIn( $fname );
1297
1298 $db =& wfGetDB( DB_MASTER );
1299
1300 // This is the revision the editor started from
1301 $baseRevision = Revision::loadFromTimestamp(
1302 $db, $this->mArticle->mTitle, $this->edittime );
1303 if( is_null( $baseRevision ) ) {
1304 wfProfileOut( $fname );
1305 return false;
1306 }
1307 $baseText = $baseRevision->getText();
1308
1309 // The current state, we want to merge updates into it
1310 $currentRevision = Revision::loadFromTitle(
1311 $db, $this->mArticle->mTitle );
1312 if( is_null( $currentRevision ) ) {
1313 wfProfileOut( $fname );
1314 return false;
1315 }
1316 $currentText = $currentRevision->getText();
1317
1318 if( wfMerge( $baseText, $editText, $currentText, $result ) ){
1319 $editText = $result;
1320 wfProfileOut( $fname );
1321 return true;
1322 } else {
1323 wfProfileOut( $fname );
1324 return false;
1325 }
1326 }
1327
1328 /**
1329 * Check if the browser is on a blacklist of user-agents known to
1330 * mangle UTF-8 data on form submission. Returns true if Unicode
1331 * should make it through, false if it's known to be a problem.
1332 * @return bool
1333 * @access private
1334 */
1335 function checkUnicodeCompliantBrowser() {
1336 global $wgBrowserBlackList;
1337 if( empty( $_SERVER["HTTP_USER_AGENT"] ) ) {
1338 // No User-Agent header sent? Trust it by default...
1339 return true;
1340 }
1341 $currentbrowser = $_SERVER["HTTP_USER_AGENT"];
1342 foreach ( $wgBrowserBlackList as $browser ) {
1343 if ( preg_match($browser, $currentbrowser) ) {
1344 return false;
1345 }
1346 }
1347 return true;
1348 }
1349
1350 /**
1351 * Format an anchor fragment as it would appear for a given section name
1352 * @param string $text
1353 * @return string
1354 * @access private
1355 */
1356 function sectionAnchor( $text ) {
1357 $headline = Sanitizer::decodeCharReferences( $text );
1358 # strip out HTML
1359 $headline = preg_replace( '/<.*?' . '>/', '', $headline );
1360 $headline = trim( $headline );
1361 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
1362 $replacearray = array(
1363 '%3A' => ':',
1364 '%' => '.'
1365 );
1366 return str_replace(
1367 array_keys( $replacearray ),
1368 array_values( $replacearray ),
1369 $sectionanchor );
1370 }
1371
1372 /**
1373 * Shows a bulletin board style toolbar for common editing functions.
1374 * It can be disabled in the user preferences.
1375 * The necessary JavaScript code can be found in style/wikibits.js.
1376 */
1377 function getEditToolbar() {
1378 global $wgStylePath, $wgContLang, $wgJsMimeType;
1379
1380 /**
1381 * toolarray an array of arrays which each include the filename of
1382 * the button image (without path), the opening tag, the closing tag,
1383 * and optionally a sample text that is inserted between the two when no
1384 * selection is highlighted.
1385 * The tip text is shown when the user moves the mouse over the button.
1386 *
1387 * Already here are accesskeys (key), which are not used yet until someone
1388 * can figure out a way to make them work in IE. However, we should make
1389 * sure these keys are not defined on the edit page.
1390 */
1391 $toolarray=array(
1392 array( 'image'=>'button_bold.png',
1393 'open' => "\'\'\'",
1394 'close' => "\'\'\'",
1395 'sample'=> wfMsg('bold_sample'),
1396 'tip' => wfMsg('bold_tip'),
1397 'key' => 'B'
1398 ),
1399 array( 'image'=>'button_italic.png',
1400 'open' => "\'\'",
1401 'close' => "\'\'",
1402 'sample'=> wfMsg('italic_sample'),
1403 'tip' => wfMsg('italic_tip'),
1404 'key' => 'I'
1405 ),
1406 array( 'image'=>'button_link.png',
1407 'open' => '[[',
1408 'close' => ']]',
1409 'sample'=> wfMsg('link_sample'),
1410 'tip' => wfMsg('link_tip'),
1411 'key' => 'L'
1412 ),
1413 array( 'image'=>'button_extlink.png',
1414 'open' => '[',
1415 'close' => ']',
1416 'sample'=> wfMsg('extlink_sample'),
1417 'tip' => wfMsg('extlink_tip'),
1418 'key' => 'X'
1419 ),
1420 array( 'image'=>'button_headline.png',
1421 'open' => "\\n== ",
1422 'close' => " ==\\n",
1423 'sample'=> wfMsg('headline_sample'),
1424 'tip' => wfMsg('headline_tip'),
1425 'key' => 'H'
1426 ),
1427 array( 'image'=>'button_image.png',
1428 'open' => '[['.$wgContLang->getNsText(NS_IMAGE).":",
1429 'close' => ']]',
1430 'sample'=> wfMsg('image_sample'),
1431 'tip' => wfMsg('image_tip'),
1432 'key' => 'D'
1433 ),
1434 array( 'image' =>'button_media.png',
1435 'open' => '[['.$wgContLang->getNsText(NS_MEDIA).':',
1436 'close' => ']]',
1437 'sample'=> wfMsg('media_sample'),
1438 'tip' => wfMsg('media_tip'),
1439 'key' => 'M'
1440 ),
1441 array( 'image' =>'button_math.png',
1442 'open' => "\\<math\\>",
1443 'close' => "\\</math\\>",
1444 'sample'=> wfMsg('math_sample'),
1445 'tip' => wfMsg('math_tip'),
1446 'key' => 'C'
1447 ),
1448 array( 'image' =>'button_nowiki.png',
1449 'open' => "\\<nowiki\\>",
1450 'close' => "\\</nowiki\\>",
1451 'sample'=> wfMsg('nowiki_sample'),
1452 'tip' => wfMsg('nowiki_tip'),
1453 'key' => 'N'
1454 ),
1455 array( 'image' =>'button_sig.png',
1456 'open' => '--~~~~',
1457 'close' => '',
1458 'sample'=> '',
1459 'tip' => wfMsg('sig_tip'),
1460 'key' => 'Y'
1461 ),
1462 array( 'image' =>'button_hr.png',
1463 'open' => "\\n----\\n",
1464 'close' => '',
1465 'sample'=> '',
1466 'tip' => wfMsg('hr_tip'),
1467 'key' => 'R'
1468 )
1469 );
1470 $toolbar ="<script type='$wgJsMimeType'>\n/*<![CDATA[*/\n";
1471
1472 $toolbar.="document.writeln(\"<div id='toolbar'>\");\n";
1473 foreach($toolarray as $tool) {
1474
1475 $image=$wgStylePath.'/common/images/'.$tool['image'];
1476 $open=$tool['open'];
1477 $close=$tool['close'];
1478 $sample = wfEscapeJsString( $tool['sample'] );
1479
1480 // Note that we use the tip both for the ALT tag and the TITLE tag of the image.
1481 // Older browsers show a "speedtip" type message only for ALT.
1482 // Ideally these should be different, realistically they
1483 // probably don't need to be.
1484 $tip = wfEscapeJsString( $tool['tip'] );
1485
1486 #$key = $tool["key"];
1487
1488 $toolbar.="addButton('$image','$tip','$open','$close','$sample');\n";
1489 }
1490
1491 $toolbar.="document.writeln(\"</div>\");\n";
1492 $toolbar.="/*]]>*/\n</script>";
1493 return $toolbar;
1494 }
1495
1496 /**
1497 * Output preview text only. This can be sucked into the edit page
1498 * via JavaScript, and saves the server time rendering the skin as
1499 * well as theoretically being more robust on the client (doesn't
1500 * disturb the edit box's undo history, won't eat your text on
1501 * failure, etc).
1502 *
1503 * @todo This doesn't include category or interlanguage links.
1504 * Would need to enhance it a bit, maybe wrap them in XML
1505 * or something... that might also require more skin
1506 * initialization, so check whether that's a problem.
1507 */
1508 function livePreview() {
1509 global $wgOut;
1510 $wgOut->disable();
1511 header( 'Content-type: text/xml' );
1512 header( 'Cache-control: no-cache' );
1513 # FIXME
1514 echo $this->getPreviewText( );
1515 /* To not shake screen up and down between preview and live-preview */
1516 echo "<br style=\"clear:both;\" />\n";
1517 }
1518
1519
1520 /**
1521 * Get a diff between the current contents of the edit box and the
1522 * version of the page we're editing from.
1523 *
1524 * If this is a section edit, we'll replace the section as for final
1525 * save and then make a comparison.
1526 *
1527 * @return string HTML
1528 */
1529 function getDiff() {
1530 global $wgUser;
1531
1532 require_once( 'DifferenceEngine.php' );
1533 $oldtext = $this->mArticle->fetchContent();
1534 $newtext = $this->mArticle->replaceSection(
1535 $this->section, $this->textbox1, $this->summary, $this->edittime );
1536 $oldtitle = wfMsg( 'currentrev' );
1537 $newtitle = wfMsg( 'yourtext' );
1538 if ( $oldtext !== false || $newtext != '' ) {
1539 $de = new DifferenceEngine( $this->mTitle );
1540 $de->setText( $oldtext, $newtext );
1541 $difftext = $de->getDiff( $oldtitle, $newtitle );
1542 } else {
1543 $difftext = '';
1544 }
1545
1546 return '<div id="wikiDiff">' . $difftext . '</div>';
1547 }
1548
1549 /**
1550 * Filter an input field through a Unicode de-armoring process if it
1551 * came from an old browser with known broken Unicode editing issues.
1552 *
1553 * @param WebRequest $request
1554 * @param string $field
1555 * @return string
1556 * @access private
1557 */
1558 function safeUnicodeInput( $request, $field ) {
1559 $text = rtrim( $request->getText( $field ) );
1560 return $request->getBool( 'safemode' )
1561 ? $this->unmakesafe( $text )
1562 : $text;
1563 }
1564
1565 /**
1566 * Filter an output field through a Unicode armoring process if it is
1567 * going to an old browser with known broken Unicode editing issues.
1568 *
1569 * @param string $text
1570 * @return string
1571 * @access private
1572 */
1573 function safeUnicodeOutput( $text ) {
1574 global $wgContLang;
1575 $codedText = $wgContLang->recodeForEdit( $text );
1576 return $this->checkUnicodeCompliantBrowser()
1577 ? $codedText
1578 : $this->makesafe( $codedText );
1579 }
1580
1581 /**
1582 * A number of web browsers are known to corrupt non-ASCII characters
1583 * in a UTF-8 text editing environment. To protect against this,
1584 * detected browsers will be served an armored version of the text,
1585 * with non-ASCII chars converted to numeric HTML character references.
1586 *
1587 * Preexisting such character references will have a 0 added to them
1588 * to ensure that round-trips do not alter the original data.
1589 *
1590 * @param string $invalue
1591 * @return string
1592 * @access private
1593 */
1594 function makesafe( $invalue ) {
1595 // Armor existing references for reversability.
1596 $invalue = strtr( $invalue, array( "&#x" => "&#x0" ) );
1597
1598 $bytesleft = 0;
1599 $result = "";
1600 $working = 0;
1601 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1602 $bytevalue = ord( $invalue{$i} );
1603 if( $bytevalue <= 0x7F ) { //0xxx xxxx
1604 $result .= chr( $bytevalue );
1605 $bytesleft = 0;
1606 } elseif( $bytevalue <= 0xBF ) { //10xx xxxx
1607 $working = $working << 6;
1608 $working += ($bytevalue & 0x3F);
1609 $bytesleft--;
1610 if( $bytesleft <= 0 ) {
1611 $result .= "&#x" . strtoupper( dechex( $working ) ) . ";";
1612 }
1613 } elseif( $bytevalue <= 0xDF ) { //110x xxxx
1614 $working = $bytevalue & 0x1F;
1615 $bytesleft = 1;
1616 } elseif( $bytevalue <= 0xEF ) { //1110 xxxx
1617 $working = $bytevalue & 0x0F;
1618 $bytesleft = 2;
1619 } else { //1111 0xxx
1620 $working = $bytevalue & 0x07;
1621 $bytesleft = 3;
1622 }
1623 }
1624 return $result;
1625 }
1626
1627 /**
1628 * Reverse the previously applied transliteration of non-ASCII characters
1629 * back to UTF-8. Used to protect data from corruption by broken web browsers
1630 * as listed in $wgBrowserBlackList.
1631 *
1632 * @param string $invalue
1633 * @return string
1634 * @access private
1635 */
1636 function unmakesafe( $invalue ) {
1637 $result = "";
1638 for( $i = 0; $i < strlen( $invalue ); $i++ ) {
1639 if( ( substr( $invalue, $i, 3 ) == "&#x" ) && ( $invalue{$i+3} != '0' ) ) {
1640 $i += 3;
1641 $hexstring = "";
1642 do {
1643 $hexstring .= $invalue{$i};
1644 $i++;
1645 } while( ctype_xdigit( $invalue{$i} ) && ( $i < strlen( $invalue ) ) );
1646
1647 // Do some sanity checks. These aren't needed for reversability,
1648 // but should help keep the breakage down if the editor
1649 // breaks one of the entities whilst editing.
1650 if ((substr($invalue,$i,1)==";") and (strlen($hexstring) <= 6)) {
1651 $codepoint = hexdec($hexstring);
1652 $result .= codepointToUtf8( $codepoint );
1653 } else {
1654 $result .= "&#x" . $hexstring . substr( $invalue, $i, 1 );
1655 }
1656 } else {
1657 $result .= substr( $invalue, $i, 1 );
1658 }
1659 }
1660 // reverse the transform that we made for reversability reasons.
1661 return strtr( $result, array( "&#x0" => "&#x" ) );
1662 }
1663
1664 function noCreatePermission() {
1665 global $wgOut;
1666 $wgOut->setPageTitle( wfMsg( 'nocreatetitle' ) );
1667 $wgOut->addWikiText( wfMsg( 'nocreatetext' ) );
1668 }
1669
1670 }
1671
1672 ?>